package com.ecut.xzh.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.ecut.xzh.constant.LengthConstant;
import com.ecut.xzh.constant.MessageConstant;
import com.ecut.xzh.context.UserHolder;
import com.ecut.xzh.dto.MarketDTO;
import com.ecut.xzh.entity.Market;
import com.ecut.xzh.exception.CustomException;
import com.ecut.xzh.mapper.MarketMapper;
import com.ecut.xzh.result.ScrollResult;
import com.ecut.xzh.service.MarketService;
import com.ecut.xzh.vo.MarketVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author XZH
 */
@Service
public class MarketServiceImpl implements MarketService {

    @Resource
    private MarketMapper marketMapper;

    /**
     * 新增商品
     *
     * @param marketDTO
     */
    @Override
    public void addGoods(MarketDTO marketDTO) {
        // 判断商品名称和图片是否为空
        if (StrUtil.isBlank(marketDTO.getName()) || StrUtil.isBlank(marketDTO.getImage())) {
            throw new CustomException(MessageConstant.GOODS_NAME_OR_IMAGE_IS_NULL);
        }

        // 赋值并加入当前学生id
        Market market = new Market();
        BeanUtil.copyProperties(marketDTO, market);
        market.setStudentId(UserHolder.getCurrentId());

        // 存入数据库
        marketMapper.insert(market);
    }

    /**
     * 滚动查询
     *
     * @param scrollNum
     * @return
     */
    @Override
    public ScrollResult scroll(Integer scrollNum) {
        PageHelper.startPage(scrollNum, LengthConstant.SCROLL_NUM);
        Page<MarketVO> scroll = marketMapper.scroll(scrollNum, LengthConstant.SCROLL_NUM);

        return new ScrollResult(scroll.getResult());
    }
}
